package com.techsoul.module.pms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.enmus.AccountingStatusEnum;
import com.techsoul.module.accounting.mapper.AccountingApMapper;
import com.techsoul.module.accounting.mapper.AccountingArCheckMapper;
import com.techsoul.module.accounting.mapper.AccountingArMapper;
import com.techsoul.module.accounting.pojo.entity.AccountingAp;
import com.techsoul.module.accounting.pojo.entity.AccountingAr;
import com.techsoul.module.accounting.pojo.entity.AccountingArCheck;
import com.techsoul.module.accounting.pojo.param.AccountingApSearchParam;
import com.techsoul.module.accounting.pojo.vo.AccountingApVo;
import com.techsoul.module.accounting.pojo.vo.AccountingArVo;
import com.techsoul.module.basic.mapper.CustomerConsigneeMapper;
import com.techsoul.module.basic.mapper.SuspiciousItemMapper;
import com.techsoul.module.basic.mapper.WarehouseMapper;
import com.techsoul.module.basic.pojo.entity.CustomerConsignee;
import com.techsoul.module.basic.pojo.entity.SuspiciousItem;
import com.techsoul.module.basic.pojo.entity.Warehouse;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.pojo.vo.WarehouseVo;
import com.techsoul.module.goods.pojo.vo.SkuVo;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.pms.enmus.InAndOutTypeEnum;
import com.techsoul.module.pms.enmus.WmsInStatusEnum;
import com.techsoul.module.pms.enmus.WmsOutStatusEnum;
import com.techsoul.module.pms.mapper.*;
import com.techsoul.module.pms.pojo.entity.*;
import com.techsoul.module.pms.pojo.param.*;
import com.techsoul.module.pms.pojo.vo.*;
import com.techsoul.module.pms.service.IBmsAllGeneralSeqTabService;
import com.techsoul.module.pms.service.ITbWmsMaterialReceiptLineService;
import com.techsoul.module.system.service.IConfigService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 入库计划明细 Service实现
 *
 * @author liuen
 * @date 2022-01-25
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class TbWmsMaterialReceiptLineServiceImpl implements ITbWmsMaterialReceiptLineService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private PmsCustomerMapper pmsCustomerMapper;
    @Autowired
    private SuspiciousItemMapper suspiciousItemMapper;
    @Autowired
    private TbWmsMaterialInLocationMapper tbWmsMaterialInLocationMapper;
    @Autowired
    private TbWmsLocationMapper tbWmsLocationMapper;
    @Autowired
    private TWmsReciptIntoLocPlanMapper tWmsReciptIntoLocPlanMapper;
    @Autowired
    private TbWmsMaterialDeliveryMapper tbWmsMaterialDeliveryMapper;
    @Autowired
    private CustomerConsigneeMapper customerConsigneeMapper;

    @Autowired
    private IBmsAllGeneralSeqTabService tBmsAllGeneralSeqTabService;
    @Autowired
    private TbWmsMaterialReceiptLineMapper mapper;
    @Autowired
    private TbWmsMaterialReceiptMapper tbWmsMaterialReceiptMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private TWhWarehouseCustomerMaterialMapper tWhWarehouseCustomerMaterialMapper;

    @Autowired
    private TbWmsMaterialDeliveryLineMapper tbWmsMaterialDeliveryLineMapper;
    @Autowired
    private AccountingApMapper accountingApMapper;
    @Autowired
    private AccountingArCheckMapper accountingArCheckMapper;
    @Autowired
    private AccountingArMapper accountingArMapper;
    @Autowired
    private ChargeConfigMapper chargeConfigMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IConfigService configService;

    @Autowired
    private TbUserWarehouseManagerMapMapper tbUserWarehouseManagerMapMapper;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(TbWmsMaterialReceiptLineSaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TbWmsMaterialReceiptLine entity = new TbWmsMaterialReceiptLine();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }
    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialReceiptLine insertEntity(TbWmsMaterialReceiptLineSaveParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TbWmsMaterialReceiptLine entity = new TbWmsMaterialReceiptLine();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        this.mapper.insert(entity);
        return entity;
    }

    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialReceiptLine generateMoveInWarehouseReceiptLine(  String orderNo,TbWmsMaterialReceiptLine receiptline,
                 WarehouseVo frwarehouse,  WarehouseVo towarehouse, UserVo user,TbWmsMaterialReceipt receipt){
        TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine = new TbWmsMaterialReceiptLine();
        BeanUtils.copyProperties(receiptline,tbWmsMaterialReceiptLine);
        //String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");

        tbWmsMaterialReceiptLine.setCustomerName(receiptline.getCustomerName()).setReceiptId(receipt.getId())
                .setOrderNo(orderNo)
                .setStageNo(towarehouse.getId())
                .setSite(towarehouse.getOrgId())
                .setStatus(receipt.getStatus())
                .setRemark(receipt.getRemark());
        tbWmsMaterialReceiptLine.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(tbWmsMaterialReceiptLine);


        return tbWmsMaterialReceiptLine;
    }

    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialReceipt generateMoveInWarehouseReceipt( String orderNo ,TbWmsMaterialReceiptLine receiptline,
                    WarehouseVo towarehouse, WarehouseVo dest,UserVo user,TbWmsMaterialReceipt receipt){
        TbWmsMaterialReceipt tbWmsMaterialReceipt = new TbWmsMaterialReceipt();

       // String orderNo = line.getOrderNo();
        tbWmsMaterialReceipt.setCustomerNo(receiptline.getCustomerNo());
        tbWmsMaterialReceipt.setCustomerName(receiptline.getCustomerName());
        tbWmsMaterialReceipt.setWarehouseCode(dest.getId());
        tbWmsMaterialReceipt.setShipperAddress(towarehouse.getAddress());
        tbWmsMaterialReceipt.setShipperPhoneNo(towarehouse.getContactPhone());
        tbWmsMaterialReceipt.setShipperContact(towarehouse.getContactName());

        tbWmsMaterialReceipt.setOrderNo("VD".concat(orderNo));
        tbWmsMaterialReceipt.setSiteCode(dest.getOrgId())
                .setStatus(WmsInStatusEnum.created.getValue());


        tbWmsMaterialReceipt.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.tbWmsMaterialReceiptMapper.insert(tbWmsMaterialReceipt);

        return tbWmsMaterialReceipt;
    }
    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDeliveryLine generateMoveInWarehouseDeliveryLine(TbWmsMaterialReceiptLine receiptline,
                 WarehouseVo towarehouse, CustomerConsignee customerConsignee,UserVo user,TbWmsMaterialDelivery tbWmsMaterialDelivery){
        TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = new TbWmsMaterialDeliveryLine();
        BeanUtils.copyProperties(receiptline,tbWmsMaterialDeliveryLine);
       if(customerConsignee!=null){
           tbWmsMaterialDeliveryLine.setDestination(customerConsignee.getAreaDesc());
           tbWmsMaterialDeliveryLine.setConsigneeAddress(customerConsignee.getConsigneeAddress());
       }else{
           tbWmsMaterialDeliveryLine.setDestination(towarehouse.getProvince());
           tbWmsMaterialDeliveryLine.setConsigneeAddress(towarehouse.getAddress());
       }
        tbWmsMaterialDeliveryLine.setDeparture(towarehouse.getCity())
                .setDeliveryId(tbWmsMaterialDelivery.getId())
                .setDestination(towarehouse.getCity())
                .setOrderNo(tbWmsMaterialDelivery.getOrderNo())
                .setUnloadDockCode(tbWmsMaterialDelivery.getConsignee())
                .setUnloadDockName(tbWmsMaterialDelivery.getConsigneeName())
                .setSite(tbWmsMaterialDelivery.getSiteCode())
                .setStatus(tbWmsMaterialDelivery.getStatus())
                .setDeparture(towarehouse.getCity())
                .setRemark(tbWmsMaterialDelivery.getRemark());
        tbWmsMaterialDeliveryLine.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.tbWmsMaterialDeliveryLineMapper.insert(tbWmsMaterialDeliveryLine);


        return tbWmsMaterialDeliveryLine;
    }

    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDelivery generateMoveInWarehouseDelivery(TbWmsMaterialReceiptLine receiptline,
                     WarehouseVo towarehouse, CustomerConsignee customerConsignee, UserVo user, TbWmsMaterialReceipt receipt){
        TbWmsMaterialDelivery tbWmsMaterialDelivery = new TbWmsMaterialDelivery();

        String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
        tbWmsMaterialDelivery.setCustomerNo(receiptline.getCustomerNo());
        tbWmsMaterialDelivery.setCustomerName(receiptline.getCustomerName());
        if(customerConsignee!=null){

            tbWmsMaterialDelivery.setConsigneeName(customerConsignee.getConsigneeName());
            tbWmsMaterialDelivery.setConsigneeAddress(customerConsignee.getConsigneeAddress());
            tbWmsMaterialDelivery.setConsigneePhoneNo(customerConsignee.getLinkManPhone());
            tbWmsMaterialDelivery.setConsigneeCity(customerConsignee.getAreaDesc());
            tbWmsMaterialDelivery.setConsignee(customerConsignee.getId());
        }
        tbWmsMaterialDelivery.setWarehouseCode(towarehouse.getId());
        tbWmsMaterialDelivery.setOrderNo("VD".concat(orderNo));
        tbWmsMaterialDelivery.setSiteCode(towarehouse.getOrgId())
                .setStatus(WmsOutStatusEnum.shipPlaned.getValue());


        tbWmsMaterialDelivery.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.tbWmsMaterialDeliveryMapper.insert(tbWmsMaterialDelivery);

        return tbWmsMaterialDelivery;
    }

    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDelivery generateDelivery
            ( String orderNo, TbWmsMaterialReceiptLine receiptline, WarehouseVo frwarehouse, WarehouseVo towarehouse, UserVo user, TbWmsMaterialReceipt tbWmsMaterialReceipt){
        TbWmsMaterialDelivery tbWmsMaterialDelivery = new TbWmsMaterialDelivery();
        BeanUtils.copyProperties(tbWmsMaterialReceipt,tbWmsMaterialDelivery);
        //String orderNo =line.getOrderNo();
        tbWmsMaterialDelivery.setCustomerNo(receiptline.getCustomerNo());
        tbWmsMaterialDelivery.setCustomerName(receiptline.getCustomerName());
        tbWmsMaterialDelivery.setWarehouseCode(frwarehouse.getId());
        // tbWmsMaterialDelivery.setConsigneeName(towarehouse.getWarehouserName());
        // tbWmsMaterialDelivery.setConsigneeAddress(towarehouse.getAddress());
        //  tbWmsMaterialDelivery.setConsigneePhoneNo(towarehouse.getContactPhone());
        tbWmsMaterialDelivery.setConsigneeCity(towarehouse.getCity());
        tbWmsMaterialDelivery.setConsigneeAddress(towarehouse.getAddress());
        tbWmsMaterialDelivery.setConsignee(towarehouse.getId());
        tbWmsMaterialDelivery.setOrderNo("VD".concat(orderNo));
        tbWmsMaterialDelivery.setSiteCode(frwarehouse.getOrgId())
                .setStatus(WmsOutStatusEnum.newRece.getValue());


        tbWmsMaterialDelivery.setId(idWorker.nextId() + "").preInsert(user.getId());
      //  this.tbWmsMaterialDeliveryMapper.insert(tbWmsMaterialDelivery);

        return tbWmsMaterialDelivery;
    }
    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDelivery generateDelivery
            ( String orderNo, TbWmsMaterialReceiptLine receiptline, WarehouseVo frwarehouse, WarehouseVo towarehouse, UserVo user, TbWmsMaterialReceipt tbWmsMaterialReceipt,TbWmsMaterialDelivery centerDelivery){
        TbWmsMaterialDelivery tbWmsMaterialDelivery = new TbWmsMaterialDelivery();
        BeanUtils.copyProperties(centerDelivery,tbWmsMaterialDelivery);
       //String orderNo =line.getOrderNo();
        tbWmsMaterialDelivery.setCustomerNo(receiptline.getCustomerNo());
        tbWmsMaterialDelivery.setCustomerName(receiptline.getCustomerName());
        tbWmsMaterialDelivery.setWarehouseCode(frwarehouse.getId());
       // tbWmsMaterialDelivery.setConsigneeName(towarehouse.getWarehouserName());
       // tbWmsMaterialDelivery.setConsigneeAddress(towarehouse.getAddress());
      //  tbWmsMaterialDelivery.setConsigneePhoneNo(towarehouse.getContactPhone());
        tbWmsMaterialDelivery.setConsigneeCity(towarehouse.getCity());

        tbWmsMaterialDelivery.setConsignee(towarehouse.getId());
        tbWmsMaterialDelivery.setOrderNo("VD".concat(orderNo));
        tbWmsMaterialDelivery.setSiteCode(frwarehouse.getOrgId());
        tbWmsMaterialDelivery.setStatus(WmsOutStatusEnum.newRece.getValue());


        tbWmsMaterialDelivery.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.tbWmsMaterialDeliveryMapper.insert(tbWmsMaterialDelivery);

        return tbWmsMaterialDelivery;
    }
    @Transactional(readOnly = false)
    @Override
    public TbWmsMaterialDeliveryLine generateDeliveryLine(String orderNo,TbWmsMaterialReceiptLine receiptline,
                                                          WarehouseVo frwarehouse, WarehouseVo towarehouse,UserVo user,
                                                          TbWmsMaterialDelivery deliverySaveParam,TbWmsMaterialDeliveryLine line){
        TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine = new TbWmsMaterialDeliveryLine();
        BeanUtils.copyProperties(line,tbWmsMaterialDeliveryLine);
        //BeanUtils.copyProperties(receiptline,tbWmsMaterialDeliveryLine);
       // String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
        tbWmsMaterialDeliveryLine.setFreightOrderNo("WMS".concat(orderNo));
        tbWmsMaterialDeliveryLine.setDeparture(frwarehouse.getCity())
                .setDeliveryId(deliverySaveParam.getId())
                .setDestination(towarehouse.getCity())
                .setOrderNo(orderNo)
                .setUnloadDockCode(deliverySaveParam.getConsignee())
                .setUnloadDockName(deliverySaveParam.getConsigneeName())
                .setMaterialNo(receiptline.getMaterialNo())
                .setMaterialName(receiptline.getMaterialName())
                .setSite(frwarehouse.getOrgId())
                .setPickUpWarehouseNo(frwarehouse.getId())
                .setStatus(deliverySaveParam.getStatus())
              //  .setDeliveryWarehouseCode(towarehouse.getWarehouserCode())
             //   .setDeliveryWarehouseName(towarehouse.getWarehouseFullName())
            //    .setDeliveryWarehouseType(towarehouse.getWarehouseType())
                .setRemark(deliverySaveParam.getRemark());
        tbWmsMaterialDeliveryLine.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.tbWmsMaterialDeliveryLineMapper.insert(tbWmsMaterialDeliveryLine);


        return tbWmsMaterialDeliveryLine;
    }




    @Transactional(readOnly = false)
    @Override
    public String moveToSuspicious(TbWmsMaterialReceiptLineSaveParam param){
        TbWmsMaterialReceiptLine item = this.mapper.selectById(param.getId());
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        item.setStatus(WmsOutStatusEnum.suspicious.getValue());
        item.preUpdate(user.getId());
        this.mapper.updateById(item);
        SuspiciousItem suspiciousItem = new SuspiciousItem();
        suspiciousItem.setDesc(param.getDesc());
        suspiciousItem.setSuspiciousType("outWarehouse");
        suspiciousItem.setOrderNo(item.getId());
        suspiciousItem.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.suspiciousItemMapper.insert(suspiciousItem);
        return suspiciousItem.getId();
    }
    @Transactional(readOnly = false)
    @Override
    public String confirm(String id){
        TbWmsMaterialReceiptLine item = this.mapper.selectById(id);
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        item.setStatus(WmsOutStatusEnum.confirmed.getValue());
        item.preUpdate(user.getId());
        this.mapper.updateById(item);

        return item.getId();
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(TbWmsMaterialReceiptLineSaveParam params) {
        TbWmsMaterialReceiptLine entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(sysUser.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public TbWmsMaterialReceiptLineVo findById(String id) {
        return this.mapper.findById(id);
    }

    @Override
    public TbWmsMaterialReceiptLineVo getWithDeliverysAndArs(String id) {
        TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo=
                this.mapper.findById(id);
        List<TbWmsMaterialInLocationVo> locationItems
                =this.tbWmsMaterialInLocationMapper.findVoByReciptLineId(id);

        List<AccountingArVo> lineArs
                =this.accountingArMapper.findBYReceLineId(id);;
        List<TbWmsMaterialDeliveryLineVo> deliverys
                =this.tbWmsMaterialDeliveryLineMapper.findByReciptLineId(id);
        List<TWmsReciptIntoLocPlanVo> putInLocs
                =this.tWmsReciptIntoLocPlanMapper.findByReciptId(id);
        tbWmsMaterialReceiptLineVo.setDeliverys(deliverys);
        tbWmsMaterialReceiptLineVo.setLineArs(lineArs);
        tbWmsMaterialReceiptLineVo.setPutInLocs(putInLocs);
        tbWmsMaterialReceiptLineVo.setLocationItems(locationItems);
        return tbWmsMaterialReceiptLineVo;
    }
    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<TbWmsMaterialReceiptLineVo> findAll(TbWmsMaterialReceiptLineSearchParam params) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TbWmsMaterialReceiptLineVo> findAll(TbWmsMaterialReceiptLineSearchParam params, Integer current, Integer pageSize) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<String> warehouseNos = new ArrayList<String>();
        warehouseNos = this.tbUserWarehouseManagerMapMapper.findAllWarehouseIds(sysUser.getId());
        params.setWarehouseNoList(warehouseNos);
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    // 按月生成客户仓储费
    @Transactional(readOnly = false)
    @Override
    public String generateArForWarehouse(String customerNo,String month)  {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        PmsCustomer pmsCustomer = this.pmsCustomerMapper.selectById(customerNo);
        pmsCustomer.setFeeGeneratedMonth(month);
        pmsCustomer.preUpdate(sysUser.getId());
        this.pmsCustomerMapper.updateById(pmsCustomer);
        ChargeConfigSearchParam chargeConfigSearchParam = new ChargeConfigSearchParam();
        chargeConfigSearchParam.setCustomerId(customerNo);
        chargeConfigSearchParam.setFrtNo("20003");
        chargeConfigSearchParam.setSettleBy("sqmt");
        chargeConfigSearchParam.setChargeTimeBy("month");
        Date st = DateUtils.parseDate(month.concat("31"));
        chargeConfigSearchParam.setStartDateFrom(DateUtils.formatDate(st));
        Date end = DateUtils.parseDate(month.concat("01"));
        chargeConfigSearchParam.setValidUntil(DateUtils.formatDate(end));
        List<ChargeConfigVo> chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
        if(chargeConfigs.size()>0){
            this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),pmsCustomer.getTotalRentedWarhouseArea(),sysUser,month);
        }else{
            chargeConfigSearchParam.setSettleBy("vol"); //按体积
            chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
            if(chargeConfigs.size()>0){
                this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),pmsCustomer.getTotalRentedWarhouseArea(),sysUser,month);
            }else{
                chargeConfigSearchParam.setSettleBy("one"); //固定按月收费
                chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
                if(chargeConfigs.size()>0){
                    this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),1.0,sysUser,month);
                }
            }
        }
        return "success";
    }
    // 按月生成全部客户仓储费
    @Transactional(readOnly = false)
    @Override
    public String generateArForWarehouse(String month)  {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<PmsCustomer> pmsCustomers =   this.pmsCustomerMapper.findAllNeedSettleThisMonth(month);
        for(int i =0;i<pmsCustomers.size();i++){
            PmsCustomer pmsCustomer = (PmsCustomer)pmsCustomers.get(i);
            pmsCustomer.setFeeGeneratedMonth(month);
            pmsCustomer.preUpdate(sysUser.getId());
            this.pmsCustomerMapper.updateById(pmsCustomer);
            ChargeConfigSearchParam chargeConfigSearchParam = new ChargeConfigSearchParam();
            chargeConfigSearchParam.setCustomerId(pmsCustomer.getId());
            chargeConfigSearchParam.setFrtNo("20003");
            chargeConfigSearchParam.setSettleBy("sqmt");
            chargeConfigSearchParam.setChargeTimeBy("month");
            Date st = DateUtils.parseDate(month.concat("31"));
            chargeConfigSearchParam.setStartDateFrom(DateUtils.formatDate(st));
            Date end = DateUtils.parseDate(month.concat("01"));
            chargeConfigSearchParam.setValidUntil(DateUtils.formatDate(end));
            List<ChargeConfigVo> chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
            if(chargeConfigs.size()>0){
                this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),pmsCustomer.getTotalRentedWarhouseArea(),sysUser,month);
            }else{
                chargeConfigSearchParam.setSettleBy("vol"); //按体积
                chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
                if(chargeConfigs.size()>0){
                    this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),pmsCustomer.getTotalRentedWarhouseArea(),sysUser,month);
                }else{
                    chargeConfigSearchParam.setSettleBy("one"); //固定按月收费
                    chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
                    if(chargeConfigs.size()>0){
                        this.getCustomerWarehouseArAmount((ChargeConfigVo)chargeConfigs.get(0),1.0,sysUser,month);
                    }
                }
            }
        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArForReceipt( List<String> idList) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        for(int i=0; i <idList.size();i++){
            TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo = this.mapper.findById((String)idList.get(i));
            ChargeConfigSearchParam chargeConfigSearchParam = new ChargeConfigSearchParam();
            chargeConfigSearchParam.setCustomerId(tbWmsMaterialReceiptLineVo.getCustomerNo());
            chargeConfigSearchParam.setFrtNo("20001");
            chargeConfigSearchParam.setInAndOutCharge(InAndOutTypeEnum.inbound.getValue());
            chargeConfigSearchParam.setMaterialNo(tbWmsMaterialReceiptLineVo.getMaterialNo());
            chargeConfigSearchParam.setStartDateFrom(DateUtils.formatDate(tbWmsMaterialReceiptLineVo.getCreateTime()));
            chargeConfigSearchParam.setValidUntil(DateUtils.formatDate(tbWmsMaterialReceiptLineVo.getCreateTime()));
            List<ChargeConfigVo> chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
            if(chargeConfigs==null||chargeConfigs.size()==0){
                chargeConfigSearchParam.setMaterialNo("*");
                chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
            }
            if(tbWmsMaterialReceiptLineVo!=null&&chargeConfigs.size()>0){
                this.getCustomerWarehouseInArAmount((ChargeConfigVo)chargeConfigs.get(0),tbWmsMaterialReceiptLineVo,sysUser);
            }

        }
        return "success";
    }

    @Transactional(readOnly = false)
    @Override
    public String generateWarehouseArForDelivery( List<String> idList) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        for(int i=0; i <idList.size();i++){
            TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo = this.tbWmsMaterialDeliveryLineMapper.findById((String)idList.get(i));
            if(tbWmsMaterialDeliveryLineVo!=null){
                if(StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getNeedSettledByLineYn())){
                    continue;
                }else{
                    ChargeConfigSearchParam chargeConfigSearchParam = new ChargeConfigSearchParam();
                    chargeConfigSearchParam.setCustomerId(tbWmsMaterialDeliveryLineVo.getSupplierNo());
                    chargeConfigSearchParam.setFrtNo("20003");
                    chargeConfigSearchParam.setInAndOutCharge(InAndOutTypeEnum.outbound.getValue());
                    chargeConfigSearchParam.setMaterialNo(tbWmsMaterialDeliveryLineVo.getMaterialNo());
                    chargeConfigSearchParam.setSettleBy(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty());
                    chargeConfigSearchParam.setChargeTimeBy("day");
                    chargeConfigSearchParam.setStartDateFrom(DateUtils.formatDate(tbWmsMaterialDeliveryLineVo.getCreateTime()));
                    chargeConfigSearchParam.setValidUntil(DateUtils.formatDate(tbWmsMaterialDeliveryLineVo.getCreateTime()));
                    List<ChargeConfigVo> chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);

                    if(chargeConfigs==null||chargeConfigs.size()==0){
                        chargeConfigSearchParam.setMaterialNo("*");
                        chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);

                    }
                    if(tbWmsMaterialDeliveryLineVo!=null&&chargeConfigs.size()>0){
                        TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo =
                                this.mapper.findById(tbWmsMaterialDeliveryLineVo.getReceivedLineId());
                        this.getCustomerWarehouseFeeArAmount
                                ((ChargeConfigVo)chargeConfigs.get(0),tbWmsMaterialDeliveryLineVo,tbWmsMaterialReceiptLineVo,sysUser);
                    }

                }

            }else{
                continue;
            }

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArForDelivery( List<String> idList) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        for(int i=0; i <idList.size();i++){
            TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo = this.tbWmsMaterialDeliveryLineMapper.findById((String)idList.get(i));
            ChargeConfigSearchParam chargeConfigSearchParam = new ChargeConfigSearchParam();
            chargeConfigSearchParam.setCustomerId(tbWmsMaterialDeliveryLineVo.getCustomerNo());
            chargeConfigSearchParam.setFrtNo("20001");
            chargeConfigSearchParam.setInAndOutCharge(InAndOutTypeEnum.outbound.getValue());
            chargeConfigSearchParam.setMaterialNo(tbWmsMaterialDeliveryLineVo.getMaterialNo());
            chargeConfigSearchParam.setStartDateFrom(DateUtils.formatDate(tbWmsMaterialDeliveryLineVo.getCreateTime()));
            chargeConfigSearchParam.setValidUntil(DateUtils.formatDate(tbWmsMaterialDeliveryLineVo.getCreateTime()));
            List<ChargeConfigVo> chargeConfigs = this.chargeConfigMapper.findAll(chargeConfigSearchParam);
            if(tbWmsMaterialDeliveryLineVo!=null&&chargeConfigs.size()>0){
                this.getCustomerWarehouseOutArAmount((ChargeConfigVo)chargeConfigs.get(0),tbWmsMaterialDeliveryLineVo,sysUser);
            }

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public Double getCustomerWarehouseArAmount(ChargeConfigVo chargeConfig, Double amt, UserVo userVo,String month) {


        Double apamt = chargeConfig.getAmount();



        apamt = NumberUtils.mul(apamt,amt);
        String apgenerateResult = this.generateArList(apamt,chargeConfig.getAmount(),amt, chargeConfig, userVo,month);
        return apamt;
    }
    @Transactional(readOnly = false)
    @Override
    public Double getCustomerWarehouseFeeArAmount(ChargeConfigVo chargeConfig,
                                                  TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo,TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo
            , UserVo userVo) {

        Double apamt = chargeConfig.getAmount();
        TbWmsMaterialDeliveryLine entityFromDb = this.tbWmsMaterialDeliveryLineMapper.selectById(tbWmsMaterialDeliveryLineVo.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + tbWmsMaterialDeliveryLineVo.getId());
        }

        BeanUtils.copyProperties(tbWmsMaterialDeliveryLineVo, entityFromDb);
        entityFromDb.setStatus(WmsOutStatusEnum.charged.getValue());
        entityFromDb.preUpdate(userVo.getId());
        this.tbWmsMaterialDeliveryLineMapper.updateById(entityFromDb);
        double days = DateUtils.getDistanceOfTwoDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getCreateTime()),tbWmsMaterialReceiptLineVo.getCreateTime());
        apamt = NumberUtils.mul(apamt,Double.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
        apamt= NumberUtils.mul(apamt,days);
        String argenerateResult = this.generateArList(apamt, tbWmsMaterialDeliveryLineVo,tbWmsMaterialReceiptLineVo, userVo);
        String apgenerateResult = this.generateApList(apamt, tbWmsMaterialDeliveryLineVo,tbWmsMaterialReceiptLineVo, userVo);
        String apcheckgenerateResult = this.generateApCheckList(apamt, tbWmsMaterialDeliveryLineVo,tbWmsMaterialReceiptLineVo, userVo);
        return apamt;
    }
    @Transactional(readOnly = false)
    @Override
    public Double getCustomerWarehouseOutArAmount(ChargeConfigVo chargeConfig, TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo, UserVo userVo) {


        Double apamt = chargeConfig.getAmount();
        TbWmsMaterialDeliveryLine entityFromDb = this.tbWmsMaterialDeliveryLineMapper.selectById(tbWmsMaterialDeliveryLineVo.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + tbWmsMaterialDeliveryLineVo.getId());
        }

        BeanUtils.copyProperties(tbWmsMaterialDeliveryLineVo, entityFromDb);
        entityFromDb.setStatus(WmsOutStatusEnum.charged.getValue());
        entityFromDb.preUpdate(userVo.getId());
        this.tbWmsMaterialDeliveryLineMapper.updateById(entityFromDb);
        apamt = NumberUtils.mul(apamt,Double.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
        String apgenerateResult = this.generateArList(apamt, tbWmsMaterialDeliveryLineVo, userVo);
        return apamt;
    }
    @Transactional(readOnly = false)
    @Override
    public Double getCustomerWarehouseInArAmount(ChargeConfigVo chargeConfig, TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo, UserVo userVo) {
        Double apamt = chargeConfig.getAmount();


        // generateApList
        TbWmsMaterialReceiptLine entityFromDb = this.mapper.selectById(tbWmsMaterialReceiptLineVo.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + tbWmsMaterialReceiptLineVo.getId());
        }

        BeanUtils.copyProperties(tbWmsMaterialReceiptLineVo, entityFromDb);
        entityFromDb.preUpdate(userVo.getId());
        entityFromDb.setStatus(WmsInStatusEnum.charged.getValue());
        this.mapper.updateById(entityFromDb);

        apamt = NumberUtils.mul(apamt,tbWmsMaterialReceiptLineVo.getQuantity());

        String apgenerateResult = this.generateArList(apamt, tbWmsMaterialReceiptLineVo, userVo);
        return apamt;
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArList(Double apamt,Double unitFee,Double qty,ChargeConfigVo chargeConfigVo,UserVo userVo,String month){
        AccountingAr accountingAp = new AccountingAr();

        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(chargeConfigVo.getId());
        accountingAp.setOrderItemNo(chargeConfigVo.getId());


        accountingAp.setCargoObjectNo(chargeConfigVo.getMaterialNo());

        accountingAp.setOriginalCustName(chargeConfigVo.getCustomerName());
        accountingAp.setPayCust(chargeConfigVo.getCustomerId());   // 付出去的 收款人
        accountingAp.setBillToCust(userVo.getCustomerId()); // 付款人
        accountingAp.setPaiedFee(0.0);
        accountingAp.setConsigneeName(chargeConfigVo.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitFee);
        accountingAp.setFrtCd("20003");
        accountingAp.setFrtNm("warehouseFee");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(month);

        accountingAp.setOriginalCustName(chargeConfigVo.getCustomerName());
        accountingAp.setRate(new BigDecimal(unitFee));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setShipperName(chargeConfigVo.getCustomerName());
        accountingAp.setSourceItemId(chargeConfigVo.getId());
        accountingAp.setWtCnt(new BigDecimal(qty));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingArMapper.insert(accountingAp);
        return "success";
    }
    @Transactional(readOnly = false)
    public String generateApList(Double apamt,TbWmsMaterialDeliveryLineVo salesOrderItem,TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo,UserVo userVo){
        AccountingAp accountingAp = new AccountingAp();
        Double unitAmt = NumberUtils.div(apamt.doubleValue(),Double.valueOf(salesOrderItem.getQuantity()));
        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(salesOrderItem.getOrderNo());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        accountingAp.setCargoObjectName(salesOrderItem.getMaterialName());
        accountingAp.setCargoObjectNo(salesOrderItem.getMaterialNo());

        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setPayCust(salesOrderItem.getCompanyNo());   // 付出去的 收款人
        accountingAp.setBillToCust(salesOrderItem.getCustomerNo()); // 付款人

        accountingAp.setConsigneeName(salesOrderItem.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitAmt);
        accountingAp.setFrtCd("20003");
        accountingAp.setFrtNm("warehouseFee");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getDeliveryId());
        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setRate(new BigDecimal(unitAmt));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(salesOrderItem.getCustomerNo());
        accountingAp.setSentToSite(salesOrderItem.getCustomerNo());
        accountingAp.setShipperName(salesOrderItem.getCustomerName());
        accountingAp.setSourceItemId(salesOrderItem.getId());
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQuantity()));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingApMapper.insert(accountingAp);
        return "success";
    }
    @Transactional(readOnly = false)
    public String generateApCheckList(Double apamt,TbWmsMaterialDeliveryLineVo salesOrderItem,TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo,UserVo userVo){
        AccountingArCheck accountingAp = new AccountingArCheck();
        Double unitAmt = NumberUtils.div(apamt.doubleValue(),Double.valueOf(salesOrderItem.getQuantity()));
        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(salesOrderItem.getOrderNo());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        accountingAp.setCargoObjectName(salesOrderItem.getMaterialName());
        accountingAp.setCargoObjectNo(salesOrderItem.getMaterialNo());

        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setPayCust(salesOrderItem.getCompanyNo());   // 付出去的 收款人
        accountingAp.setBillToCust(salesOrderItem.getCustomerNo()); // 付款人

        accountingAp.setConsigneeName(salesOrderItem.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitAmt);
        accountingAp.setFrtCd("20003");
        accountingAp.setFrtNm("warehouseFee");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getDeliveryId());
        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setRate(new BigDecimal(unitAmt));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(salesOrderItem.getCustomerNo());
        accountingAp.setShipperName(salesOrderItem.getCustomerName());
        accountingAp.setSourceItemId(salesOrderItem.getId());
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQuantity()));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingArCheckMapper.insert(accountingAp);
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArList(Double apamt,TbWmsMaterialDeliveryLineVo salesOrderItem,TbWmsMaterialReceiptLineVo tbWmsMaterialReceiptLineVo,UserVo userVo){
        AccountingAr accountingAp = new AccountingAr();
        Double unitAmt = NumberUtils.div(apamt.doubleValue(),Double.valueOf(salesOrderItem.getQuantity()));
        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(salesOrderItem.getOrderNo());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        accountingAp.setCargoObjectName(salesOrderItem.getMaterialName());
        accountingAp.setCargoObjectNo(salesOrderItem.getMaterialNo());

        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setPayCust(salesOrderItem.getCustomerNo());   // 付出去的 收款人
        accountingAp.setBillToCust(userVo.getCustomerId()); // 付款人
        accountingAp.setPaiedFee(0.0);
        accountingAp.setConsigneeName(salesOrderItem.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitAmt);
        accountingAp.setFrtCd("20003");
        accountingAp.setFrtNm("warehouseFee");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getDeliveryId());
        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
         accountingAp.setRate(new BigDecimal(unitAmt));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setShipperName(salesOrderItem.getCustomerName());
        accountingAp.setSourceItemId(salesOrderItem.getId());
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQuantity()));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingArMapper.insert(accountingAp);
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArList(Double apamt,TbWmsMaterialDeliveryLineVo salesOrderItem,UserVo userVo){
        AccountingAr accountingAp = new AccountingAr();
        Double unitAmt = NumberUtils.div(apamt.doubleValue(),Double.valueOf(salesOrderItem.getQuantity()));
        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(salesOrderItem.getOrderNo());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        accountingAp.setCargoObjectName(salesOrderItem.getMaterialName());
        accountingAp.setCargoObjectNo(salesOrderItem.getMaterialNo());

        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setPayCust(salesOrderItem.getCustomerNo());   // 付出去的 收款人
        accountingAp.setBillToCust(userVo.getCustomerId()); // 付款人
        accountingAp.setPaiedFee(0.0);
        accountingAp.setConsigneeName(salesOrderItem.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitAmt);
        accountingAp.setFrtCd("20001");
        accountingAp.setFrtNm("warehouseDis");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getDeliveryId());
        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setRate(new BigDecimal(unitAmt));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setShipperName(salesOrderItem.getCustomerName());
        accountingAp.setSourceItemId(salesOrderItem.getId());
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQuantity()));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingArMapper.insert(accountingAp);
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateArList(Double apamt,TbWmsMaterialReceiptLineVo salesOrderItem,UserVo userVo){
        AccountingAr accountingAp = new AccountingAr();
        Double unitAmt = NumberUtils.div(apamt.doubleValue(),salesOrderItem.getQuantity());
        accountingAp.setAmount(apamt);
        accountingAp.setBasicNo(salesOrderItem.getOrderNo());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        accountingAp.setCargoObjectName(salesOrderItem.getMaterialName());
        accountingAp.setCargoObjectNo(salesOrderItem.getMaterialNo());

        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setPayCust(salesOrderItem.getCustomerNo());   // 付出去的 收款人
        accountingAp.setBillToCust(userVo.getCustomerId()); // 付款人
        accountingAp.setPaiedFee(0.0);
        accountingAp.setConsigneeName(salesOrderItem.getCustomerName());
        accountingAp.setContractAmount(apamt);
        accountingAp.setContractRate(unitAmt);
        accountingAp.setFrtCd("20001");
        accountingAp.setFrtNm("warehouseDis");
        accountingAp.setInputType("A");
        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getReceiptId());
        accountingAp.setOriginalCustName(salesOrderItem.getCustomerName());
        accountingAp.setRate(new BigDecimal(unitAmt));
        accountingAp.setRemainedAmount(apamt);
        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setShipperName(salesOrderItem.getCustomerName());
        accountingAp.setSourceItemId(salesOrderItem.getId());
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQuantity()));
        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.accountingArMapper.insert(accountingAp);
        return "success";
    }


    @Transactional(readOnly = false)
    @Override
    public String importData(MultipartFile file) {
        List<TbWmsMaterialReceiptLineVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(TbWmsMaterialReceiptLineVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }

        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        TbWmsMaterialReceiptLineSaveParam entity = new TbWmsMaterialReceiptLineSaveParam();
        for (TbWmsMaterialReceiptLineVo data : dataList) {
            successNum++;
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterial = this.tWhWarehouseCustomerMaterialMapper.findByMaterialNoAndCustomerNo(data.getMaterialNo(),data.getCustomerNo());
            if(tWhWarehouseCustomerMaterial==null){
                tWhWarehouseCustomerMaterial = new TWhWarehouseCustomerMaterial();
                BeanUtils.copyProperties(data, tWhWarehouseCustomerMaterial);
                tWhWarehouseCustomerMaterial.setMaterialNo(data.getMaterialNo());
                tWhWarehouseCustomerMaterial.setVehicleModel(data.getMaterialNo());
                tWhWarehouseCustomerMaterial.setMeasUnitNo("辆");
                tWhWarehouseCustomerMaterial.setId(idWorker.nextId() + "").preInsert(user.getId());
                this.tWhWarehouseCustomerMaterialMapper.insert(tWhWarehouseCustomerMaterial);
            }
            Warehouse warehouse  = warehouseMapper.findByCode(data.getStageNo());
            String warehouseId = null;
            if(StringUtils.isNull(warehouse)){
                warehouse = new Warehouse();
                warehouse.setWarehouserCode(data.getStageNo());
                warehouse.setWarehouserName(data.getStageNo());
                warehouse.setWarehouseType("center");
                warehouse.setId(idWorker.nextId() + "").preInsert(user.getId());
                warehouseMapper.insert(warehouse);
                warehouseId = warehouse.getId();
            }else{
                warehouseId = warehouse.getId();
            }
            CustomerConsignee customerConsignee = this.customerConsigneeMapper.findByCode(data.getConsigneeNo());
            if(customerConsignee==null){
                customerConsignee = new CustomerConsignee();
                customerConsignee.setCustomerNo(data.getCustomerNo());
                customerConsignee.setCcccode(data.getConsigneeNo());
                customerConsignee.setConsigneeAddress(data.getConsigneeName());
                customerConsignee.setWarehouseCode(warehouseId);
                customerConsignee.setConsigneeName(data.getConsigneeName());
                customerConsignee.setIsValid("1");
                customerConsignee.setId(idWorker.nextId() + "").preInsert(user.getId());
                this.customerConsigneeMapper.insert(customerConsignee);
            }
            TbWmsMaterialReceipt tbWmsMaterialReceipt = new TbWmsMaterialReceipt();
            /*BeanUtils.copyProperties(params, entity);*/
            // 新增运单主表信息
            if(StringUtils.isNull(tbWmsMaterialReceipt.getOrderNo())){
                String orderNo = tBmsAllGeneralSeqTabService.generateNo("materialDelivery");
                tbWmsMaterialReceipt.setOrderNo("R".concat(orderNo));
            }
            tbWmsMaterialReceipt.setCustomerNo("1000");

            tbWmsMaterialReceipt.setWarehouseCode(warehouseId);
            tbWmsMaterialReceipt.setStatus("created");
            tbWmsMaterialReceipt.setId(idWorker.nextId() + "").preInsert(user.getId());

            tbWmsMaterialReceiptMapper.insert(tbWmsMaterialReceipt);



            BeanUtils.copyProperties(data, entity);
            entity.setStageNo(warehouseId);
            entity.setConsigneeNo(customerConsignee.getId());
            entity.setConsigneeAddress(customerConsignee.getConsigneeAddress());
            entity.setConsigneeName(customerConsignee.getConsigneeName());
            entity.setConsigneePhoneNo(customerConsignee.getLinkManMobile());
            entity.setStatus("created");
            entity.setVehicleLoadType(tWhWarehouseCustomerMaterial.getMaterialType());

            if(tWhWarehouseCustomerMaterial.getHeight()!=null){
                entity.setHigh(tWhWarehouseCustomerMaterial.getHeight().doubleValue());
            }
            if(tWhWarehouseCustomerMaterial.getLength()!=null){
                entity.setLength(tWhWarehouseCustomerMaterial.getLength().doubleValue());
            }
            if(tWhWarehouseCustomerMaterial.getWidth()!=null){
                entity.setWidth(tWhWarehouseCustomerMaterial.getWidth().doubleValue());
            }

            entity.setReceiptType("vehicle");
            entity.setSite(user.getOrgId());
            entity.setMaterialName(data.getVehicleBrand());
            if(StringUtils.isNull(customerConsignee.getWarehouseArea())){
                entity.setAreaNo("临时过渡库区");
            }else{

                entity.setAreaNo(customerConsignee.getWarehouseArea());

            }
            entity.setReceiptId(tbWmsMaterialReceipt.getId());
            entity.setOrderNo(tbWmsMaterialReceipt.getOrderNo());
            entity.setReceiveHourTime(entity.getReceivedTime()+" "+entity.getReceiveHourTime());


            TbWmsLocationSearchParam locationSearchParam = new TbWmsLocationSearchParam();
            locationSearchParam.setStatus("empty");
            locationSearchParam.setWarehouseCode(warehouseId);
            locationSearchParam.setLocationName(entity.getCenterName());
            //locationSearchParam.setArea(entity.getAreaNo());

            //List<TbWmsLocation> locations = this.tbWmsLocationMapper.findAllEntity(new Page<>(1, 5),locationSearchParam).getRecords();
            List<TbWmsLocation> locations = this.tbWmsLocationMapper.findAllEntity2(locationSearchParam);
            /*if(locations==null||locations.size()==0){
                throw new BusinessException("导入的经销商没有配置入库仓库和相应库区，请先在系统中配置该经销商的入库仓库和库区");
            }*/
            if(locations==null||locations.size()==0){
                throw new BusinessException("导入的真实库位没有找到对应的仓库，请先在系统中配置对应的仓库、库区、库位");
            }
            TbWmsLocation tbWmsLocation= (TbWmsLocation)locations.get(0);
            entity.setAreaNo(tbWmsLocation.getArea());
            entity.setLocationNo(tbWmsLocation.getLocationNo());
            TbWmsMaterialReceiptLine entity1 = insertEntity(entity);
            entity.setId(entity1.getId());


            TbWmsMaterialInLocation materialInLocation = new TbWmsMaterialInLocation();
            TbWmsMaterialInLocation tbWmsMaterialInLocation = new TbWmsMaterialInLocation();
            tbWmsMaterialInLocation.setLocationNo(tbWmsLocation.getLocationNo());
            tbWmsMaterialInLocation.setSkuCode(entity.getSkuCode());
            tbWmsMaterialInLocation.setWarehouseCode(entity.getStageNo());
            tbWmsMaterialInLocation.setArea(entity.getAreaNo());
            tbWmsMaterialInLocation.setCustomerId(entity.getCustomerNo());
            tbWmsMaterialInLocation.setMaterialNo(entity.getMaterialNo());
            tbWmsMaterialInLocation.setMaterialName(entity.getMaterialName());
            tbWmsMaterialInLocation.setReceivedLineId(entity.getId());
            tbWmsMaterialInLocation.setSiteCode(entity.getSite());
            tbWmsMaterialInLocation.setStatus(WmsInStatusEnum.inposition.getValue());
            tbWmsMaterialInLocation.setId(idWorker.nextId() + "").preInsert(user.getId());
            this.tbWmsMaterialInLocationMapper.insert(tbWmsMaterialInLocation);
            itemNo = itemNo++;
            if(!entity.getAreaNo().equals("临时过渡库区")){
                tbWmsLocation.setStatus("full");
                tbWmsLocation.preUpdate(user.getId());
                this.tbWmsLocationMapper.updateById(tbWmsLocation);
            }

        }

        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");


        return successMsg.toString();
    }

    @Override
    public String exportData(TbWmsMaterialReceiptLineSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "入库单导出.xlsx";

        List<TbWmsMaterialReceiptLineVo> list = this.findAll(params);
        try {
            new ExcelExport(null, TbWmsMaterialReceiptLineVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("入库单导出", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }

}
